package com.kk.使用Condition控制线程通信;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * the class of Plan1ThreadsAndJUC
 *
 * <p>
 * .
 *
 * @author little_lunatic
 * @date 2023-03-07
 */
public class ConditionDemo {
    private final Lock lock = new ReentrantLock();
    private String name;
    private int count = 1;
    private boolean flag = false;
    /**
     * 创建代表生产者方面的Condition对象
     */
    private Condition condition_pro = lock.newCondition();
    /**
     * 创建代表消费者方面的Condition对象
     */
    private Condition condition_con = lock.newCondition();

    public static void main(String[] args) {
        ConditionDemo demo = new ConditionDemo();

        ExecutorService executorService = Executors.newCachedThreadPool();
        AtomicInteger i = new AtomicInteger();
        while (true) {
            executorService.submit(() -> demo.set("PRO--" + i.getAndIncrement()));

            executorService.submit(() -> {
                try {
                    demo.out();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            executorService.submit(() -> demo.set("PRO--" + i.getAndIncrement()));

            executorService.submit(() -> {
                try {
                    demo.out();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

    }

    public void set(String name) {
        lock.lock();
        try {
            while (flag) {
                condition_pro.await(); //生产者线程在conndition_pro对象上等待
            }
            this.name = name;
            System.out.println("...生产者..." + this.name);
            flag = true;
            condition_con.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //unlock()要放在finally块中。
        }
    }

    public void out() throws InterruptedException {
        lock.lock(); //锁住此语句与lock.unlock()之间的代码
        try {
            while (!flag) {
                condition_con.await(); //消费者线程在conndition_con对象上等待
            }
            System.out.println("...消费者..." + this.name);
            flag = false;
            condition_pro.signalAll(); /*唤醒所有在condition_pro对象下等待的线程，也就是唤醒所有生产者线程*/
        } finally {
            lock.unlock();
        }
    }
}
